package day10.test2;

class product {
    private int num;
    private int people_num;

    public product(int num) {
        this.num = num;
        this.people_num = 0;
    }

    public synchronized boolean add_num() {
        if (this.num > 0) {
            this.num--;
            return true;
        } else {
            return false;
        }
    }

    public synchronized boolean add_people_num() {
        if (this.people_num < 3) {
            this.people_num++;
            return true;
        } else {
            return false;
        }
    }
}

class TestThread extends Thread {
    private product product;
    private String name;

    public TestThread(day10.test2.product product, String name) {
        this.product = product;
        this.name = name;
    }

    @Override
    public void run() {
        if (this.product.add_num()) {
            System.out.println(this.name + " 成功加入购物车!");
            if (this.product.add_people_num()) {
                System.out.println(this.name + " 成功付款!");
            } else {
                System.out.println(this.name + " 没有成功付款!");
            }
        } else {
            System.out.println(this.name + " 没有成功加入购物车!");
        }
    }
}

public class Test {
    public static void main(String[] args) throws InterruptedException {
        product product = new product(3);
        TestThread[] threads = new TestThread[5];
        String[] shopper = {"num1", "num2", "num3", "num4", "num5"};

        for (int i = 0; i < 5; i++) {
            threads[i] = new TestThread(product, shopper[i]);
            threads[i].start();
        }

        for (Thread thread : threads) {
            thread.join();
        }
    }
}
